import { ipcMain } from "electron";
import { get, getJson, getText, post, postJson, postText, type RequestOptions } from "@elec/main/util/http-utils.ts";
import type { DownloadParam } from "@common/http-types.ts";
import { DownloadTask } from "@elec/main/task/download-task.ts";
import { getWindow } from "@elec/main/util/window-holder.ts";

(() => {
  ipcMain.handle("http.get", (_, url: string, options?: RequestOptions) => get(url, options).then(res => res.arrayBuffer()));
  ipcMain.handle("http.getText", (_, url: string, options?: RequestOptions) => getText(url, options));
  ipcMain.handle("http.getJson", (_, url: string, options?: RequestOptions) => getJson(url, options));

  ipcMain.handle("http.post", (_, url: string, options?: RequestOptions) => post(url, options).then(res => res.arrayBuffer()));
  ipcMain.handle("http.postText", (_, url: string, body: any, options?: RequestOptions) => postText(url, body, options));
  ipcMain.handle("http.postJson", (_, url: string, body: any, options?: RequestOptions) => postJson(url, body, options));

  ipcMain.on("http.download", (event, param: DownloadParam) => {
    DownloadTask.submit(param.id, param.url, param.savePath, getWindow(event.sender.id));
  });
  ipcMain.on("http.download.cancel", (_, taskId: string) => {
    DownloadTask.cancel(taskId);
  });
})();
